const axios = require('axios');
const { v4: uuidv4 } = require('uuid');
const { getCachedCookie, getCsrfToken } = require('../core/login');

const http = axios.create({
  proxy: false,
});

http.interceptors.request.use((config) => {
    console.log(config.params);
    if (config.method === 'get' && config.params) {
    const keys = Object.keys(config.params);
    config.url += '?';
    keys.forEach((key) => {
      config.url += `${key}=${encodeURIComponent(config.params[key])}&`;
    });
    config.params = {};
  }

  if (config.method.toLowerCase() !== 'get') {
    config.headers['x-replay-context'] = `${new Date().getTime()}:${uuidv4()}`
  }

  if (config.needAuth) {
    config.headers.hpmAuth = true;
    const cookie = getCachedCookie();
    if (cookie) {
      const hpmCsrfToken = getCsrfToken(cookie);
      config.headers.Cookie = cookie;
      config.headers.hpmCsrfToken = hpmCsrfToken;
    }
  }
  return config;
});

http.interceptors.response.use(
  async (res) => {
    const { data } = res;
    if (data.code && data.code !== 200) {
      if (data.code === 302) {
      
      }
    }
    return res;
  },
  (error) => {
    throw error;
  }
);

module.exports = http;
